package com.wfg.bigdata.spark.core.wc1

import org.apache.spark.rdd.RDD
import org.apache.spark.{SparkConf, SparkContext}

object Spark02_WordCount {

  def main(args: Array[String]): Unit = {

    // 建立spark 框架的链接
    val spc = new SparkConf().setMaster("local").setAppName("workcount")
    val sc = new SparkContext(spc)

    //1.读取文件
    val lines: RDD[String] = sc.textFile("datas")
    val words: RDD[String] = lines.flatMap(_.split(" "))
    val wordToOne: RDD[(String, Int)] = words.map(word => (word, 1))
    val wordGroup: RDD[(String,Iterable[(String,Int)])] = wordToOne.groupBy(t => t._1)
    val res: RDD[(String, Int)] = wordGroup.map {
      case (str, list) => {
        list.reduce {
          (t1, t2) => {
            (t1._1, t1._2 + t2._2)
          }
        }
      }
    }

    //5.将转换的结果采集到控制台打印出来
    val array: Array[(String, Int)] = res.collect()
    array.foreach(println)
    sc.stop();
  }
}
